//--------------------------------------------------------------------------------------
// File: Tutorial07.fx
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
Texture3D voxelTexture : register( t1 );
SamplerState voxelSamplerLinear : register( s1 );


//--------------------------------------------------------------------------------------

struct VS_INPUT
{
    uint z8_y8_x8_null4_edge4 : TEXCOORD0;
    
};
struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float3 Normal : NORMAL;
	float4 Color : COLOR;
    
};

//--------------------------------------------------------------------------------------
// Geometry Shader
//--------------------------------------------------------------------------------------


float3 VertexInterp(float3 p1, float3 p2, float val1, float val2)
{
    float mu = (0.5f - val1) / (val2 - val1);
    float3 p = lerp(p1, p2, mu);
    return p;
}


//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
VS_OUTPUT VS( VS_INPUT input )
{
	float texelSize = 1.0f / 33.0f;
    VS_OUTPUT output = (VS_OUTPUT)0;
	uint3 unpacked_coord;
	uint caseNum = input.z8_y8_x8_null4_edge4 & 0xFF;
	unpacked_coord.x = (input.z8_y8_x8_null4_edge4 >>  8) & 0xFF;
	unpacked_coord.y = (input.z8_y8_x8_null4_edge4 >> 16) & 0xFF;
	unpacked_coord.z = (input.z8_y8_x8_null4_edge4 >> 24) & 0xFF;
	float2 vol;
	float3 theOtherCoord;
	if( (caseNum & 1) > 0)
		theOtherCoord = float3(1, 0, 0);
	else if( (caseNum & 2) > 0)
		theOtherCoord = float3(0, 1, 0);
	else if( (caseNum & 4) > 0)
		theOtherCoord = float3(0, 0, 1);
		
	float4 val0 = voxelTexture.SampleLevel(voxelSamplerLinear, texelSize * (unpacked_coord + 0.5f), 0);
    float4 val1 = voxelTexture.SampleLevel(voxelSamplerLinear, texelSize * (unpacked_coord + 0.5f + theOtherCoord), 0);
	
	output.Pos = float4(VertexInterp(float3(unpacked_coord), float3(unpacked_coord) + theOtherCoord, val0.r, val1.r), 0);
	//output.Pos = float4(unpacked_coord, 0);
	
    output.Normal = caseNum;//float3(0.4f,0.2f,0.1f);
    
	output.Color = 0.12345f;

    
    return output;
}
[maxvertexcount(1)]
void GS( point VS_OUTPUT input[1], inout PointStream<VS_OUTPUT> triStream )
{
	VS_OUTPUT o;
	o.Pos = input[0].Pos;
	o.Normal = input[0].Normal;
	o.Color = input[0].Color;

	triStream.Append(o);

	
}
